package com.chinamsp.dydb.convert.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.chinamsp.dydb.convert.ORMNameStrategy;

/**
 * 默认的 model 和 dao 名称处理策略
 * 
 * @author shifenghu
 *
 */
@Component("DefaultNameStrategy")
public class DefaultNameStrategy implements ORMNameStrategy {

	@Override
	public String convertToDao(String modelClassName) {
		Assert.notNull(modelClassName, "要转换的mode类名不能为空");
	    String className = modelClassName + DAO_SUFFIX;
        //将 model 换成 dao
        return className.replace(".model.", ".dao.");
	}

	@Override
	public String convertToModel(String daoClassName) {
		Assert.notNull(daoClassName, "要转换的dao类名不能为空");
		//截取名称
		String className = daoClassName.substring(0, daoClassName.length() - 3);
		//dao 换成model
		className = className.replace(".dao.", ".model.");
		return className;
	}

	@Override
	public String convertToField(String property) {
		Assert.notNull(property, "要转换的字段/表名不能为空");
		Matcher matcher = Pattern.compile(PRO_TO_FIELD_PATTERN).matcher(property);
		StringBuffer sb = new StringBuffer();
		// 逐个替换
		while(matcher.find()){
			matcher.appendReplacement(sb, "_$0");
		}
		// 最后一段或者失败的字段直接添加
		matcher.appendTail(sb);
		// 如果 第一个字符是_，则忽略
		if(sb.charAt(0) == '_'){
			sb.deleteCharAt(0);
		}
		return sb.toString().toLowerCase();
	}

	@Override
	public String convertToSchema(String modelClassName) {
		return convertToField(modelClassName);
	}

	@Override
	public String convertToBiz(String modelClassName) {
		Assert.notNull(modelClassName, "要转换的mode类名不能为空");
	    String className = modelClassName + BIZ_SUFFIX;
        //将 model 换成 dao
        return className.replace(".model.", ".biz.");
	}

	@Override
	public String parseModuleName(String tableName) {
		return tableName.indexOf(SEPARATOR) == -1 ? tableName : tableName.substring(0, tableName.indexOf(SEPARATOR));
	}
	
	/**
	 * 驼峰转下划线正则
	 */
	private static final String PRO_TO_FIELD_PATTERN = "[A-Z]+";

	/**
	 * dao 后缀
	 */
	private static final String DAO_SUFFIX = "Dao";

	/**
	 * biz 后缀
	 */
	private static final String BIZ_SUFFIX = "Biz";

	/**
	 * 分隔符
	 */
	private static final char SEPARATOR = '_';
}
